const sqlite3 = require('sqlite3').verbose();

const dbname = 'mysqlite';
const db = new sqlite3.Database(dbname)

db.serialize(() => {
    const sql = `
        CREATE TABLE IF NOT EXISTS articles
        (id integer primary key,title,keys,appid)
    `;
    db.run(sql);
});

// Articles API Calss
class Articles {
    static all(cb) {
        db.all('SELECT * FROM articles', cb);
    }
    static find(id, cb) {
        db.get('SELECT * FROM articles WHERE id = ?', id, cb);
    }
    static create(data, cb) {
        const sql = `
                INSERT INTO 
                articles(title,appid,keys) 
                VALUES(?,?,?) 
                ;select last_insert_rowid();`;
        db.run(sql, data.title, data.appid, data.keys, cb);
    }
    static delete(id, cb) {
        if (!id) return cb(new Error(`缺少参数id`));
        db.run('DELETE FROM articles WHERE id=?', id, cb)
    }
    static update(data, cb) {
        const sql = `
            UPDATE articles
            SET title=?,content=?
            WHERE id=?
        `
        db.run(sql, data.title, data.content, data.id, cb)
    }
}
module.exports.Articles = Articles;